package com.itheima.reggie.exception;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler1(SQLIntegrityConstraintViolationException e) {
        log.info("[用户访问过程中出现了:违反完整性约束性的异常]");
        log.error(e.getMessage());
        // Duplicate entry 'dada' for key 'idx_username'是 唯一性收到影响了.
        //  Column ‘XXX’ cannot be null   非空原因
        // 用户访问的问题 用不用给发邮件 发短信
        // 直接告诉用户他的问题
        if (e.getMessage().contains("Duplicate entry")) {
            // Duplicate entry 'dada' for key 'idx_username'
            String[] split = e.getMessage().split(" ");
            return R.error("您写的" + split[2] + "已经存在");
        } else if (e.getMessage().contains("cannot be null")) {
            return R.error("您填写的字段不能为空");
        } else {
            // 我们记录在日志
            return R.error("未知错误");
        }
    }

    // zhis yichang  is  wangfang zhongfu
    @ExceptionHandler(CustomException.class)
    public R<String> CustomExceptionHandler(CustomException c) {
        log.info("[关联逻辑外键错误]");
        log.error(c.getMessage());
        return R.error(c.getMessage());
    }
}
